package com.atguigu.gulimall.ware.rabbit.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.order.OrderTo;
import com.atguigu.common.to.ware.WareSkuLockedTO;
import com.atguigu.gulimall.ware.rabbit.constant.WareConstant;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderEntity;
import com.atguigu.gulimall.ware.vo.OrderResp;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description
 * @Author lhj
 * @Date 2024/5/18 14:49
 */
@Slf4j
@Component
@RabbitListener(queues = WareConstant.STOCK_RELEASE_QUEUE)
public class WareSkuLockedListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 库存自动解锁
     *
     * @param WareSkuLockedTo 库存信息to
     * @param message         message
     * @param channel         channel
     */
    @RabbitHandler
    public void wareLockedReceive(WareSkuLockedTO WareSkuLockedTo, Message message, Channel channel) {
        log.info("wareLockedReceive locked ware to: {}", JSONObject.toJSONString(WareSkuLockedTo));
        try {
            //解锁库存操作
            wareSkuService.releaseStockLocked(WareSkuLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("wareLockedReceive unlocked field exception", e);
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ex) {
                log.error("wareLockedReceive connection mq server field exception", ex);
            }
        }
    }

    /**
     * 订单关闭发送消息解锁库存
     *
     * @param order   订单信息
     * @param message 消息
     * @param channel 信道
     * @throws IOException 异常
     */
    @RabbitHandler
    public void handlerOrderReleaseUnLockStock(OrderTo order, Message message, Channel channel) throws IOException {
        try {
            log.info("handling order release unlock stock order: {}", JSONObject.toJSONString(order));
            wareSkuService.orderLeaseUnLockStock(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("Unexpected exception when handling  order release unlock stock field orderSn: {} exception", order.getOrderSn(), e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
